<template>
    <v-dialog v-model="dialogFormVisible" max-width="800px" persistent scrollable>
        <v-card class="elevation-10 pa-2">
            <v-card-title class="d-flex align-center"> Edit </v-card-title>

            <v-card-text>
                <v-form ref="formRef" v-model="formValid">
                    <v-row>
                        <v-col cols="12" md="6">
                            <v-text-field
                                v-model="form.name"
                                :rules="rules.name"
                                density="compact"
                                hide-details="auto"
                                label="渠道名称"
                                required
                                variant="outlined"
                            />
                        </v-col>
                        <v-col cols="12" md="6">
                            <v-text-field
                                v-model="form.remark"
                                :rules="rules.remark"
                                density="compact"
                                hide-details="auto"
                                label="备注"
                                variant="outlined"
                            />
                        </v-col>
                    </v-row>
                </v-form>
            </v-card-text>

            <v-card-actions>
                <v-spacer />
                <v-btn color="grey-darken-1" variant="text" @click="close"> Cancel </v-btn>
                <v-btn :loading="saving" color="primary" variant="text" @click="save"> Confirm </v-btn>
            </v-card-actions>
        </v-card>
    </v-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, nextTick, onMounted } from 'vue';
import { doInsert, doUpdate, type TenantChannelModel, type ApiResponse } from '@/api/tenant/channel/TenantChannelManagementApi';
import { isNull } from '@/utils/validate';
import { formateDate } from '@/utils/format';
import { validatorRule } from '@/utils/validateRule';
import { getDictListSync } from '@/utils/dict';
import { useMessage } from '@/composables/useMessage';

const { success: showSuccess, error: showError } = useMessage();

// 基础数据
const dialogFormVisible = ref(false);
const title = ref('');
const formValid = ref(false);
const formRef = ref();
const saving = ref(false);
const defaultFrom: TenantChannelModel = {
    name: '',
    remark: '',
    createBy: '',
    createTime: ''
};

// 表单数据
const form = reactive<Partial<TenantChannelModel>>(defaultFrom);

// 字典数据
const dict = reactive({});

// 验证规则
const rules = {
    name: [(v: any) => !!v || '渠道名称不能为空'],
    remark: [],
    createBy: [(v: any) => !!v || '创建者不能为空'],
    createTime: [(v: any) => !!v || '创建时间不能为空']
};

// 事件发射
const emit = defineEmits<{
    fetchData: [];
}>();

// 显示编辑对话框
function showEdit(row?: TenantChannelModel) {
    if (!row) {
        title.value = '添加渠道配置';
        // 重置表单为默认值
        Object.assign(form, defaultFrom);
    } else {
        title.value = '编辑渠道配置';
        // 复制行数据到表单，处理日期格式
        const formData = { ...row };

        Object.assign(form, formData);
    }

    dialogFormVisible.value = true;
}

// 关闭对话框
function close() {
    dialogFormVisible.value = false;
    nextTick(() => {
        if (formRef.value) {
            formRef.value.reset();
        }
        // 重置表单数据
        Object.assign(form, defaultFrom);
    });
}

// 保存
async function save() {
    if (!formRef.value) return;

    try {
        const { valid } = await formRef.value.validate();
        if (!valid) return;

        saving.value = true;

        // 处理表单数据
        const submitData = { ...form } as TenantChannelModel;
        handlerFormData(submitData);

        let response: ApiResponse<TenantChannelModel>;

        // 编辑模式
        if (!isNull(submitData.id)) {
            let { msg } = await doUpdate(submitData);
            showSuccess(msg || 'update success');
        } else {
            // 新增模式
            let { msg } = await doInsert(submitData);
            showSuccess(msg || 'add success');
        }

        // 通知父组件刷新数据
        emit('fetchData');
        close();
    } catch (error) {
        console.error('save failed:', error);
        showError('save failed');
    } finally {
        saving.value = false;
    }
}

// 处理表单数据
function handlerFormData(formData: any) {
    if (!isNull(formData)) {
        for (const key in formData) {
            // 对于时间类进行处理
            if (Object.prototype.toString.call(formData[key]) === '[object Date]') {
                formData[key] = formateDate(formData[key], 'yyyy-MM-dd hh:mm:ss');
            }
            // 处理datetime-local格式
            else if (typeof formData[key] === 'string' && formData[key].includes('T')) {
                formData[key] = formData[key].replace('T', ' ') + ':00';
            }
        }
    }
}

// 初始化字典数据
function initDict() {}

// 暴露方法
defineExpose({
    showEdit
});

// 生命周期
onMounted(() => {
    initDict();
});
</script>

<style lang="scss" scoped>
:deep(.v-dialog) {
    .v-card-title {
        background-color: rgb(var(--v-theme-primary));
        color: white;
    }
}
</style>
